package com.chen.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.annotation.Resource;

@EnableResourceServer
@Configuration
public class ResourceServer extends ResourceServerConfigurerAdapter {

    @Resource
    private TokenStore tokenStore;

    // 资源服务id，当前资源服务的唯一标识符，可选项
    public static final String RESOURCE_ID = "res1";


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {

        resources
                // 验证资源服务id
                .resourceId(RESOURCE_ID)
                // 资源服务在本地完成校验 jwt token
                .tokenStore(tokenStore)
                // 验证令牌服务
                // .tokenServices(tokenServices())
                .stateless(true);
    }

    // 设置资源的访问保护
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/**").access("#oauth2.hasScope('ROLE_API')")
                .and().csrf().disable()
                // 不创建也不使用 session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    // // 验证令牌的服务
    // @Bean
    // public ResourceServerTokenServices tokenServices(){
    //     // 使用远程服务请求授权服务器校验token,必须指定校验token的url、client_id，client_secret
    //     RemoteTokenServices tokenServices = new RemoteTokenServices();
    //     tokenServices.setCheckTokenEndpointUrl("http://localhost:8111/oauth/check_token");
    //     tokenServices.setClientId("client");
    //     tokenServices.setClientSecret("112233");
    //     return tokenServices;
    // }
}
